package com.asa.mvvm_aop_frame.basic.aspect

import android.app.Activity
import android.util.Log
import com.asa.mvvm_aop_frame.basic.AppStackManager
import com.asa.mvvm_aop_frame.basic.pointcut.ActivityLifecyclePoint.ON_ACTIVITY_START
import com.asa.mvvm_aop_frame.basic.pointcut.ActivityLifecyclePoint.ON_ACTIVITY_STOP
import com.asa.mvvm_aop_frame.basic.ui.BaseActivity
import org.aspectj.lang.JoinPoint
import org.aspectj.lang.annotation.After
import org.aspectj.lang.annotation.Aspect

/**
 * create By：anderson
 * on 2022/4/27
 * desc:
 */
@Aspect
class BackgroundAspect {


    @After(ON_ACTIVITY_START)
    fun toForegroundAspect(joinPoint: JoinPoint){
        try {
            Log.e("日志", "toForegroundAspect: background")
            if (joinPoint.`this` !is BaseActivity<*, *>) {
                throw IllegalStateException("joinPoint is not BaseActivity")
            }
            AppStackManager.instance.setAppCount(AppStackManager.instance.getAppCount() + 1)
            if (AppStackManager.instance.getRunInBackground()) {
                //应用从后台回到前台 需要做的操作
                AppStackManager.instance.setRunInBackground(false)
                val baseActivity = joinPoint.`this` as BaseActivity<*, *>
                val application = baseActivity.application
                val declaredMethod =
                    application.javaClass.getDeclaredMethod("toForeground", Activity::class.java)
                declaredMethod.invoke(application, baseActivity)
            }
        } catch (e: Exception) {

        }
    }


    @After(ON_ACTIVITY_STOP)
    fun toBackgroundAspect(joinPoint: JoinPoint){
        try {
            if (joinPoint.`this` !is BaseActivity<*, *>) {
                throw IllegalStateException("joinPoint is not BaseActivity")
            }
            AppStackManager.instance.setAppCount(AppStackManager.instance.getAppCount() - 1)
            if (AppStackManager.instance.getAppCount() == 0) {
                //应用进入后台 需要做的操作
                AppStackManager.instance.setRunInBackground(true)
                val baseActivity = joinPoint.`this` as BaseActivity<*, *>
                val application = baseActivity.application
                val declaredMethod =
                    application.javaClass.getDeclaredMethod("toBackground", Activity::class.java)
                declaredMethod.invoke(application, baseActivity)
            }
        } catch (e: Exception) {

        }
    }

}